package com.xiaoxin.smartbi.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/queue")
@Slf4j
public class QueueController {

    @Resource
    ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(()->{
            System.out.println(name+"执行中，执行人："+Thread.currentThread().getName());
            try {
                Thread.sleep(600000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },threadPoolExecutor);
    }

    @GetMapping("/get")
    public String get(){
        Map<String,Object> map=new HashMap<>();
        //任务总数
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("任务总数",taskCount);
        //完成任务数
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("完成任务数",completedTaskCount);
        //工作线程数
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("工作线程数",activeCount);
        //队列大小
        int size = threadPoolExecutor.getQueue().size();
        map.put("队列大小",size);
        String jsonStr = JSONUtil.toJsonStr(map);
        return jsonStr;
    }
}
